﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RCREEE.Library;
using RCREEE.Library.Entities;
using RCREEE.Web.Classes;

namespace RCREEE.Web
{
    public partial class Login : System.Web.UI.Page
    {
        public User User
        {
            get
            {
                if (Session[SessionStrings.SS_User] != null)
                    return (User)Session[SessionStrings.SS_User];

                return new User();
            }
            set
            {
                Session[SessionStrings.SS_User] = value;

            }
        }
        public string ReturnURL
        {
            get
            {
                return Request[QueryStrings.QS_ReturnURL];
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {

                string userName = tbUserName.Text.Trim();

                string password = tbPassword.Text.Trim();
                int langCode = 1033;
                
                if(Session[SessionStrings.SS_LanguageCode] != null)
                    langCode = int.Parse(Session[SessionStrings.SS_LanguageCode].ToString());

                User = DataManager.GetUser(userName, password, langCode);

                if (User != null && User.UserId > 0)
                {
                    Session[SessionStrings.SS_UserId] = User.UserId.ToString();
                    Session[SessionStrings.SS_IsAdmin] = User.IsAdmin.ToString();

                    Session[SessionStrings.SS_Permissions] = DataManager.ToDataTable(User.UserPermissions);

                    if (!string.IsNullOrEmpty(ReturnURL))
                    {
                        Response.Redirect(ReturnURL);
                    }

                    Response.Redirect("Default.aspx");
                }

                else
                    lblError.Text = "Wrong data";

            }

            catch (Exception exc)
            {
                lblError.Text = "Wrong data";
            }
        }
    }
}